<template>
  <div v-if="!closed" class="chat-window" :class="{ 'chat-window--minimized': minimized }">
    <div class="chat-header" @click="toggleMinimize">
      <div class="chat-title">
        <span class="chat-icon">💬</span>
        <span class="chat-title-text">AI 助手</span>
      </div>
      <div class="chat-controls">
        <button class="control-button" @click.stop="minimized = !minimized">
          <span class="icon">{{ minimized ? '▲' : '▼' }}</span>
        </button>
        <button class="control-button" @click.stop="closeChatWindow">
          <span class="icon">✕</span>
        </button>
      </div>
    </div>
    <div class="chat-body">
      <div class="chat-messages" ref="messagesRef">
        <div v-for="(message, index) in messages" 
             :key="index" 
             class="message"
             :class="message.role">
          <div class="message-avatar">
            {{ message.role === 'assistant' ? '🤖' : '👤' }}
          </div>
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>
      <div class="chat-input">
        <textarea
          ref="inputRef"
          v-model="inputMessage"
          placeholder="输入消息..."
          @keydown.enter.prevent="sendMessage"
          :rows="1"
          :disabled="sending"
        ></textarea>
        <button 
          class="send-button"
          @click="sendMessage"
          :disabled="!inputMessage.trim() || sending"
        >
          <span class="icon">{{ sending ? '⏳' : '↗️' }}</span>
        </button>
      </div>
    </div>
  </div>
  
  <!-- 悬浮按钮，当聊天窗口关闭时显示 -->
  <div v-else class="chat-float-button" @click="reopenChatWindow">
    <span class="chat-float-icon">💬</span>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch, onBeforeUnmount } from 'vue';
import type { ConversationMessage } from '../../types/dialogue';
import { dialogueAnalysisApi } from '../../api/dialogueAnalysis';
import type { DialogueTurn } from '../../types/analysis';

const props = defineProps<{
  initialMessages?: ConversationMessage[];
  dialogueTurns: DialogueTurn[];
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'reopen'): void;
}>();

const minimized = ref(false);
const closed = ref(false);
const inputMessage = ref('');
const sending = ref(false);
const messages = ref<ConversationMessage[]>([]);
const messagesRef = ref<HTMLDivElement | null>(null);
const inputRef = ref<HTMLTextAreaElement | null>(null);
const userRole = ref<string>('');
const hasSetRole = ref(false);
let currentResponse = '';

const toggleMinimize = () => {
  minimized.value = !minimized.value;
};

const closeChatWindow = () => {
  closed.value = true;
  emit('close');
};

const reopenChatWindow = () => {
  closed.value = false;
  emit('reopen');
};

const formatTime = (timestamp?: string) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  });
};

const scrollToBottom = async () => {
  await nextTick();
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight;
  }
};

const handleWebSocketMessage = (message: string) => {
  if (sending.value) {
    // 在发送状态下，将消息追加到当前响应
    currentResponse += message;
    
    // 更新最后一条AI消息的内容
    if (messages.value.length > 0) {
      const lastMessage = messages.value[messages.value.length - 1];
      if (lastMessage.role === 'assistant') {
        lastMessage.content = currentResponse;
      }
    }
    scrollToBottom();
  } else {
    // 非发送状态下，检查是否有最后一条AI消息，如果有则追加内容
    if (messages.value.length > 0) {
      const lastMessage = messages.value[messages.value.length - 1];
      if (lastMessage.role === 'assistant') {
        // 追加到最后一条AI消息
        lastMessage.content += message;
      } else {
        // 如果最后一条不是AI消息，则添加新消息
        messages.value.push({
          role: 'assistant',
          content: message,
          timestamp: new Date().toISOString()
        });
      }
    } else {
      // 如果没有消息，则添加新消息
      messages.value.push({
        role: 'assistant',
        content: message,
        timestamp: new Date().toISOString()
      });
    }
    scrollToBottom();
  }
};

const handleWebSocketError = (error: string) => {
  sending.value = false;
  messages.value.push({
    role: 'assistant',
    content: `错误: ${error}`,
    timestamp: new Date().toISOString()
  });
  scrollToBottom();
};

const handleRoleSetup = (message: string) => {
  if (!hasSetRole.value) {
    userRole.value = message.trim();
    hasSetRole.value = true;
    // 设置角色后初始化对话内容
    nextTick(() => {
      initializeDialogue();
    });
  }
};

const sendMessage = async () => {
  const content = inputMessage.value.trim();
  if (!content || sending.value) return;

  // 如果还没有设置角色，只保存角色不发送消息
  if (!hasSetRole.value) {
    handleRoleSetup(content);
    messages.value.push({
      role: 'user',
      content,
      timestamp: new Date().toISOString()
    });
    inputMessage.value = '';
    return;
  }

  sending.value = true;
  currentResponse = '';
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content,
    timestamp: new Date().toISOString()
  });
  
  // 清空输入框并滚动到底部
  inputMessage.value = '';
  await nextTick();
  scrollToBottom();

  // 添加一个空的AI消息，等待流式响应填充
  messages.value.push({
    role: 'assistant',
    content: '',
    timestamp: new Date().toISOString()
  });

  try {
    await dialogueAnalysisApi.sendMessage(
      content,
      userRole.value,
      messages.value.length > 4 // 如果不是第一条消息，则为继续对话
    );
    
    // 等待一段时间后，如果没有收到消息，则结束发送状态
    setTimeout(() => {
      if (sending.value) {
        sending.value = false;
        // 如果最后一条消息是空的，则添加一个默认消息
        const lastMessage = messages.value[messages.value.length - 1];
        if (lastMessage.role === 'assistant' && !lastMessage.content.trim()) {
          lastMessage.content = '抱歉，我没有收到回复。请重试。';
          scrollToBottom();
        }
      }
    }, 10000); // 10秒超时
  } catch (error) {
    // 移除空的AI消息
    messages.value.pop();
    
    // 添加错误消息
    messages.value.push({
      role: 'error',
      content: `发送消息失败: ${error}`,
      timestamp: new Date().toISOString()
    });
    sending.value = false;
    scrollToBottom();
  }
};

// 初始化消息
const initializeMessages = () => {
  if (props.initialMessages && props.initialMessages.length > 0) {
    messages.value = [...props.initialMessages];
  } else if (messages.value.length === 0) {
    const initialMessage: ConversationMessage = {
      role: 'assistant',
      content: '您好！请问您在本次对话中扮演的角色是谁？',
      timestamp: new Date().toISOString()
    };
    messages.value.push(initialMessage);
  }
};

// 初始化WebSocket连接
const initializeWebSocket = async () => {
  try {
    // 确保之前的连接已关闭
    dialogueAnalysisApi.disconnect();
    
    // 建立新的连接
    await dialogueAnalysisApi.connect();
    
    // 设置消息处理器
    dialogueAnalysisApi.onMessage(handleWebSocketMessage);
    dialogueAnalysisApi.onError(handleWebSocketError);
    dialogueAnalysisApi.onOpen(() => {
      console.log('WebSocket connected successfully');
    });
  } catch (error) {
    console.error('Failed to initialize WebSocket:', error);
    handleWebSocketError('连接失败，请稍后重试');
  }
};

// 初始化对话内容
const initializeDialogue = () => {
  console.log('初始化对话内容:', props.dialogueTurns);
  const content = props.dialogueTurns.map(turn => `${turn.speaker}: ${turn.text}`).join('\n');
  console.log('初始化对话内容:', content);
  dialogueAnalysisApi.sendMessage(content, userRole.value, false);
};

// 监听消息变化，自动滚动到底部
watch(() => messages.value.length, scrollToBottom);

// 组件挂载时初始化
onMounted(() => {
  initializeMessages();
  initializeWebSocket();
  scrollToBottom();
  if (inputRef.value) {
    inputRef.value.focus();
  }
});

// 组件卸载前断开连接
onBeforeUnmount(() => {
  dialogueAnalysisApi.disconnect();
});

// 监听closed状态变化，当重新打开聊天窗口时重新连接WebSocket
watch(closed, async (newValue) => {
  if (!newValue) {
    // 重新打开聊天窗口时，重新初始化WebSocket连接
    await initializeWebSocket();
  }
});
</script>

<style lang="scss" scoped>
.chat-window {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  width: 360px;
  background: white;
  border-radius: 1rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  max-height: calc(100vh - 4rem);
  transition: all 0.3s ease;
  z-index: 1000;

  &--minimized {
    height: auto;

    .chat-body {
      display: none;
    }
  }

  .chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    background: linear-gradient(135deg, #6d28d9, #7c3aed);
    color: white;
    cursor: pointer;
    user-select: none;

    .chat-title {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      font-weight: 500;

      .chat-icon {
        font-size: 1.25rem;
      }

      .chat-title-text {
        font-size: 1rem;
      }
    }

    .chat-controls {
      display: flex;
      gap: 0.5rem;

      .control-button {
        background: none;
        border: none;
        color: white;
        cursor: pointer;
        padding: 0.25rem;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 0.25rem;
        transition: background-color 0.2s ease;

        &:hover {
          background: rgba(255, 255, 255, 0.1);
        }

        .icon {
          font-size: 0.875rem;
        }
      }
    }
  }

  .chat-body {
    display: flex;
    flex-direction: column;
    height: 400px;

    .chat-messages {
      flex: 1;
      overflow-y: auto;
      padding: 1rem;
      display: flex;
      flex-direction: column;
      gap: 1rem;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: #f3f4f6;
        border-radius: 3px;
      }

      &::-webkit-scrollbar-thumb {
        background: #d1d5db;
        border-radius: 3px;

        &:hover {
          background: #9ca3af;
        }
      }

      .message {
        display: flex;
        gap: 0.75rem;
        max-width: 85%;

        &.assistant {
          align-self: flex-start;

          .message-content {
            background: #f3f4f6;
            border-radius: 1rem 1rem 1rem 0;
          }
        }

        &.user {
          align-self: flex-end;
          flex-direction: row-reverse;

          .message-content {
            background: #6d28d9;
            color: white;
            border-radius: 1rem 1rem 0 1rem;

            .message-time {
              color: rgba(255, 255, 255, 0.7);
            }
          }
        }

        &.error {
          align-self: flex-start;

          .message-content {
            background: #f3f4f6;
            border-radius: 1rem 1rem 1rem 0;
            color: #ef4444;
          }
        }

        .message-avatar {
          width: 2rem;
          height: 2rem;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f3f4f6;
          font-size: 1rem;
        }

        .message-content {
          padding: 0.75rem 1rem;
          font-size: 0.875rem;
          line-height: 1.5;

          .message-text {
            margin-bottom: 0.25rem;
          }

          .message-time {
            font-size: 0.75rem;
            color: #6b7280;
          }
        }
      }
    }

    .chat-input {
      padding: 1rem;
      border-top: 1px solid #e5e7eb;
      display: flex;
      gap: 0.75rem;
      background: white;

      textarea {
        flex: 1;
        border: 1px solid #e5e7eb;
        border-radius: 0.5rem;
        padding: 0.625rem;
        font-size: 0.875rem;
        resize: none;
        outline: none;
        transition: border-color 0.2s ease;
        line-height: 1.5;
        max-height: 100px;

        &:focus {
          border-color: #6d28d9;
        }

        &:disabled {
          background: #f3f4f6;
          cursor: not-allowed;
        }
      }

      .send-button {
        padding: 0.625rem;
        background: #6d28d9;
        color: white;
        border: none;
        border-radius: 0.5rem;
        cursor: pointer;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        justify-content: center;

        &:hover:not(:disabled) {
          background: #5b21b6;
          transform: translateY(-1px);
        }

        &:disabled {
          background: #9ca3af;
          cursor: not-allowed;
        }

        .icon {
          font-size: 1.125rem;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .chat-window {
    bottom: 1rem;
    right: 1rem;
    left: 1rem;
    width: auto;
    max-width: none;

    .chat-body {
      height: 50vh;
    }
  }
}

@media (prefers-color-scheme: dark) {
  .chat-window {
    background: #1f2937;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);

    .chat-header {
      background: linear-gradient(135deg, #7c3aed, #8b5cf6);
    }

    .chat-body {
      .chat-messages {
        &::-webkit-scrollbar-track {
          background: #374151;
        }

        &::-webkit-scrollbar-thumb {
          background: #4b5563;

          &:hover {
            background: #6b7280;
          }
        }

        .message {
          &.assistant {
            .message-content {
              background: #374151;
              color: #e5e7eb;

              .message-time {
                color: #9ca3af;
              }
            }
          }

          &.user {
            .message-content {
              background: #7c3aed;
            }
          }

          &.error {
            .message-content {
              background: #374151;
              color: #ef4444;
            }
          }

          .message-avatar {
            background: #374151;
          }
        }
      }

      .chat-input {
        border-top-color: #374151;
        background: #1f2937;

        textarea {
          background: #374151;
          border-color: #4b5563;
          color: #e5e7eb;

          &::placeholder {
            color: #9ca3af;
          }

          &:focus {
            border-color: #7c3aed;
          }

          &:disabled {
            background: #4b5563;
          }
        }

        .send-button {
          background: #7c3aed;

          &:hover:not(:disabled) {
            background: #8b5cf6;
          }

          &:disabled {
            background: #6b7280;
          }
        }
      }
    }
  }
}

// 悬浮按钮样式
.chat-float-button {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  width: 3.5rem;
  height: 3.5rem;
  background: linear-gradient(135deg, #6d28d9, #7c3aed);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  z-index: 1000;
  transition: all 0.3s ease;
  
  &:hover {
    transform: scale(1.05);
    box-shadow: 0 6px 10px -1px rgba(0, 0, 0, 0.1), 0 4px 6px -1px rgba(0, 0, 0, 0.06);
  }
  
  .chat-float-icon {
    font-size: 1.5rem;
    color: white;
  }
}

@media (prefers-color-scheme: dark) {
  .chat-float-button {
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.2);
    
    &:hover {
      box-shadow: 0 6px 10px -1px rgba(0, 0, 0, 0.2), 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
  }
}
</style>
